﻿using System;
using System.Web;
using Actya.Core.Infrastructure;
using Autofac.Integration.Mvc;

namespace Actya.Web.Infrastructure
{
	public class CmsApplicationHttpModule : IHttpModule
	{
		private readonly static object Locker = new object();

		public void Init(HttpApplication context)
		{
            context.BeginRequest += BeginRequest;
			context.EndRequest += OnEndRequest;
		}

        private void BeginRequest(object sender, EventArgs e)
        {
        	var cmsHost = CmsHost.GetInstance();
            if (cmsHost.ApplicationState != ApplicationState.Started)
            {
                lock (Locker)
                {
					if (cmsHost.ApplicationState != ApplicationState.Started)
                    {
                        var context = sender as HttpApplication;
                        cmsHost.Start(context);
                    }
                }
            }
        }

		/// <summary>
		/// Gets the lifetime scope provider that should be notified when a HTTP request ends.
		/// </summary>
		internal static ILifetimeScopeProvider LifetimeScopeProvider { get; private set; }

		public static void SetLifetimeScopeProvider(ILifetimeScopeProvider lifetimeScopeProvider)
		{
			if (lifetimeScopeProvider == null) throw new ArgumentNullException("lifetimeScopeProvider");

			LifetimeScopeProvider = lifetimeScopeProvider;
		}

		static void OnEndRequest(object sender, EventArgs e)
		{
			if (LifetimeScopeProvider != null)
				LifetimeScopeProvider.EndLifetimeScope();
		}

		public void Dispose()
		{
		}
	}
}